﻿using System.Reflection;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using CodeContrib.Web.Routing;

namespace CodeContrib.Web.Mvc.Html
{
	public static class FormExtensions
	{
		public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formAction, FormMethod method)
		{
			return BeginForm(htmlHelper, formAction, method, null);
		}

		public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formAction, object htmlAttributes)
		{
			return BeginForm(htmlHelper, formAction, FormMethod.Post, htmlAttributes);
		}

		public static MvcForm BeginForm(this HtmlHelper htmlHelper, string formAction, FormMethod method, object htmlAttributes)
		{
			var type = typeof (System.Web.Mvc.Html.FormExtensions);
			var bindings = BindingFlags.NonPublic | BindingFlags.Static;

			var methodInfo = type.GetMethod("FormHelper", bindings);

			return methodInfo.Invoke(null, new object[]
				                               {
					                               htmlHelper, formAction, method, htmlAttributes.ToHtmlAttributes()
				                               }) as MvcForm;
		}

		public static MvcForm BeginForm(this HtmlHelper htmlHelper, FormMethod method)
		{
			return htmlHelper.BeginForm(null, null, method);
		}

		public static MvcForm BeginForm(this HtmlHelper htmlHelper, object routeValues, FormMethod method)
		{
			return htmlHelper.BeginForm(null, null, routeValues, method);
		}

		public static MvcForm BeginForm(this HtmlHelper htmlHelper, object routeValues, FormMethod method, object htmlAttributes)
		{
			return htmlHelper.BeginForm(null, null, routeValues.ToRouteValueDictionary(), method, htmlAttributes.ToHtmlAttributes());
		}
	}
}